﻿using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Magic.Core;

/// <summary>
/// 数据库上下文对象
/// </summary>
public static class SugarContext
{
    internal static void InitConnectionConfigs(List<ConnectionConfig> connectionConfigs)
    {
        ConnectionConfigs = connectionConfigs;
    }

    private static List<ConnectionConfig> ConnectionConfigs;
    /// <summary>
    /// SqlSugar 数据库实例
    /// </summary>
    public static SqlSugarScope Instance => new(
        ConnectionConfigs
        , db =>
        {
            AopSetting(db);
        });


    private static void AopSetting(SqlSugarClient db)
    {
        //执行超时时间
        db.Ado.CommandTimeOut = 30;

        db.Aop.OnLogExecuting = (sql, pars) =>
        {
            if (sql.StartsWith("SELECT"))
            {
                Console.ForegroundColor = ConsoleColor.Green;
            }
            if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
            {
                Console.ForegroundColor = ConsoleColor.White;
            }
            if (sql.StartsWith("DELETE"))
            {
                Console.ForegroundColor = ConsoleColor.Blue;
            }
            Console.WriteLine($"DB:Sql:\r\n\r\n {UtilMethods.GetSqlString(DbType.MySql, sql, pars)}");
            Console.ResetColor();
        };
        db.Aop.DataExecuting = (oldValue, entityInfo) =>
        {
            // 新增操作
            if (entityInfo.OperationType == DataFilterType.InsertByObject)
            {

                if (entityInfo.PropertyName == "Createtime")
                    entityInfo.SetValue(Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds));
            }
            // 更新操作
            if (entityInfo.OperationType == DataFilterType.UpdateByObject)
            {
                if (entityInfo.PropertyName == "Updatetime")
                    entityInfo.SetValue(Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds));

            }
        };
    }
}
